package org.project.choujiang.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import org.project.choujiang.pojo.ro.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("file")
public class FileController {
    @Value("${files.upload.path}")
    private String pathPrefix;

    @Value("${files.upload.urlPrefix}")
    private String urlPrefix;

    /**
     * 图片上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String uuid = UUID.fastUUID().toString();
        String filePath = pathPrefix + uuid;
        File output = new File(filePath);
        file.transferTo(output);
        return R.success(urlPrefix+uuid);
    }

    /**
     * 图片预览
     * @param id
     * @param resp
     * @throws IOException
     */
    @GetMapping("view/{id}")
    public void view(@PathVariable String id, HttpServletResponse resp) throws IOException {
        String filePath = pathPrefix + id;
        IoUtil.copy(new FileInputStream(filePath),resp.getOutputStream());
    }

}
